package com.jn.erp.wechat.staff.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jn.erp.common.annotation.Log;
import com.jn.erp.common.core.result.AjaxResult;
import com.jn.erp.common.enums.BusinessType;
import com.jn.erp.web.api.student.entity.Student;
import com.jn.erp.web.api.student.entity.StudentClass;
import com.jn.erp.web.api.student.entity.StudentContactRecord;
import com.jn.erp.web.api.student.entity.dto.EnrollmentStuDto;
import com.jn.erp.web.api.student.entity.dto.StudentBaseInfoDTO;
import com.jn.erp.web.api.student.entity.dto.TStudentCourseDto;
import com.jn.erp.web.api.student.entity.vo.StudentCourseVo;
import com.jn.erp.web.api.student.entity.vo.TStudentCourseVo;
import com.jn.erp.web.api.student.entity.vo.TransferOrderVo;
import com.jn.erp.web.api.student.service.StudentClassService;
import com.jn.erp.web.api.student.service.StudentContactRecordService;
import com.jn.erp.web.api.student.service.StudentCourseService;
import com.jn.erp.web.api.student.service.StudentService;
import com.jn.erp.wechat.common.api.controller.base.BaseWxAuthController;
import com.jn.erp.wechat.core.WxTableDataInfo;
import com.jn.erp.wechat.common.api.entity.dto.WxUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <pre>
 * 学员/线索管理/跟进管理 相关接口管理
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/9/10 19:52
 */
@RestController
@RequestMapping("/wx/student")
public class MpStudentController extends BaseWxAuthController {

    @Autowired
    private StudentService studentService;


    @Autowired
    private StudentClassService studentClassService;

    @Autowired
    private StudentContactRecordService studentContactRecordService;

    @Autowired
    private StudentCourseService studentCourseService;

    //-------------------------------------线索管理 学员管理-在读---------------------
    /**
     * 在读学员2 历史5 线索1    /student/list
     *
     */
    @GetMapping("/list")
    public WxTableDataInfo studentList(Student student) {
        WxUserDto wxUser = getWxUser();
        student.setOrgId(wxUser.getOrgIdLong());
        student.setDeleted(0);
        startPage();
        List<Student> list = studentService.getList(student);
        return getWxDataTable(list);
    }
    /**
     * 编辑新增学员基本信息  /student/save
     *
     * @param studentDTO
     * @return
     */
    @Log(title = "编辑新增学员基本信息", businessType = BusinessType.UPDATE)
    @PostMapping("/save")
    @Transactional
    public AjaxResult saveStudent(@RequestBody StudentBaseInfoDTO studentDTO) {
        //        获取登录者信息
        WxUserDto wxUser = getWxUser();
        studentDTO.setOrgId(wxUser.getOrgIdLong());
        if(studentDTO.getCreator()==null){
            studentDTO.setCreator(getUserId());
        }
        Long stu = studentService.studentUnifysaveOrUpdateByDTO(studentDTO);
        return success(stu);

    }


    /**
     * 删除线索学员  彻底删除 还原   /student/deleteClue
     */
    @Log(title = "删除线索学员", businessType = BusinessType.DELETE)
    @PostMapping("/deleteClue")
    public AjaxResult delete(@RequestBody Student student) {
        studentService.deleteClue(student);
        return success("操作成功");
    }


    /**
     * 分配跟进人，学管师    /student/getCounselor
     *
     */
    @Log(title = "分配跟进人，学管师", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('sales:clue:follow')")
    @PostMapping("/getCounselor")
    public AjaxResult getCounselor(@RequestBody Student student) {
        studentService.getCounselor(student);
        return AjaxResult.success("分配成功");
    }

    //-------------------------------------跟进管理 ---------------------
    /**
     * 跟进管理大列表   /student/followList
     *
     * @param studentContactRecord
     * @return
     */
    @GetMapping("/followList")
    public WxTableDataInfo followList(StudentContactRecord studentContactRecord) {
        //        获取登录者信息
        WxUserDto wxUser = getWxUser();
        studentContactRecord.setOrgId(wxUser.getOrgIdLong());
        startPage();
        List<StudentContactRecord> records = studentContactRecordService.followList(studentContactRecord);
        return getWxDataTable(records);
    }


    /**
     * 跟进管理 添加和修改跟进记录    /student/followSave
     *
     * @param
     * @param
     * @return
     */
    @Log(title = "跟进管理 添加和修改跟进记录", businessType = BusinessType.UPDATE)
    @PostMapping("/followSave")
    public AjaxResult followSave(@RequestBody StudentContactRecord studentContactRecord) {
        //        获取登录者信息
        WxUserDto wxUser = getWxUser();
        studentContactRecord.setOrgId(wxUser.getOrgIdLong());
        studentContactRecord.setCounselorId(String.valueOf(wxUser.getUserId()));
        if (studentContactRecordService.saveOrUpdateByRecord(studentContactRecord)) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.error("操作失败");
        }
    }


    /**
     * 删除跟进学员     /student/followDelete
     *
     * @param studentContactRecord
     * @return
     */
    @Log(title = "删除跟进学员", businessType = BusinessType.DELETE)
    @PostMapping("/followDelete")
    public AjaxResult followDelete(@RequestBody StudentContactRecord studentContactRecord) {
        long id = studentContactRecord.getId();
        StudentContactRecord byId = studentContactRecordService.getById(id);
        long studentId = byId.getStudentId();
        Student student = studentService.getById(studentId);
        student.setDeleted(1);
        studentService.updateById(student);
        UpdateWrapper<StudentContactRecord> up = new UpdateWrapper();
        up.set("deleted", 1);
        up.eq("student_id", studentId);
        studentContactRecordService.update(up);
        return AjaxResult.success("删除成功");
    }




    //-------------------------------------报读情况 ---------------------
    /**
     * 报读情况列表    /student/enrollmentStatus
     *
     * @return
     */
    @GetMapping("/enrollmentStatus")
    public WxTableDataInfo enrollmentStatus(EnrollmentStuDto student) {
        //        获取登录者信息
        WxUserDto wxUser = getWxUser();
        //        1, 意向学员 2, 在学学员 3 结业学员 4.报读学员 5.历史学员
        startPage();
        student.setOrgId(wxUser.getOrgIdLong());
        List<EnrollmentStuDto> list = studentService.enrollmentList(student);
        return getWxDataTable(list);
    }

    /**
     * 统计剩余课时，剩余金额    /student/remainderCount
     *
     */
    @PostMapping("/remainderCount")
    public AjaxResult remainderCount(@RequestBody EnrollmentStuDto student) {
        WxUserDto wxUser = getWxUser();
        student.setOrgId(wxUser.getOrgIdLong());
        EnrollmentStuDto remainderCount =  studentService.remainderCount(student);
        return AjaxResult.success(remainderCount);
    }

    //-------------------------------------学员详情 ---------------------
    /**
     * 学员详情基本信息    /student/getStudent
     */
    @PostMapping("/getStudent")
    public AjaxResult getStudent(@RequestBody Student student) {
        //        获取登录者信息
        WxUserDto wxUser = getWxUser();
        // 机构id报读
        student.setOrgId(wxUser.getOrgIdLong());
        Student stu = studentService.getStudent(student);
        return success(stu);
    }


    /**
     * 删除跟进记录   /student/followDeleteRecord
     *
     * @param studentContactRecord
     * @return
     */
    @Log(title = "删除跟进记录", businessType = BusinessType.DELETE)
    @PostMapping("/followDeleteRecord")
    public AjaxResult followDeleteRecord(@RequestBody StudentContactRecord studentContactRecord) {
        long id = studentContactRecord.getId();
        StudentContactRecord byId = studentContactRecordService.getById(id);
        long studentId = byId.getStudentId();
        // 查询有几条跟进记录
        QueryWrapper<StudentContactRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted",0);
        wrapper.eq("student_id",studentId);
        wrapper.eq("org_id",Long.parseLong(loginDeptAuth()));
        List<StudentContactRecord> list = studentContactRecordService.list(wrapper);
        if (list.size()>1) {
            byId.setDeleted(1);
            studentContactRecordService.updateById(byId);
        }else {
            return AjaxResult.error("不能删除最后一条跟进记录");
        }
        return AjaxResult.success("删除成功");
    }

    //---------------------------财务报名续费-----------------------------


    /**
     * 全部学员 （家分页）   /student/allStudentList
     *
     * @param student
     * @return
     */
    @GetMapping("/allStudentList")
    public WxTableDataInfo allStudentList(Student student) {
        WxUserDto wxUser = getWxUser();
        student.setOrgId(wxUser.getOrgIdLong());
        startPage();
        List<Student> stu = studentService.studentList(student);
        return getWxDataTable(stu);
    }


    /**
     * 报名回显接口
     * 前端传学生id  /student/applicationOne
     *
     * @param
     * @return
     */
    @PostMapping("/applicationOne")
    public AjaxResult applicationOne(@RequestBody Student student) {
        WxUserDto wxUser = getWxUser();
        student.setOrgId(wxUser.getOrgIdLong());
        Student stu = studentService.applicationOne(student);
        if (stu == null) {
            return success("暂无数据");
        }
        return AjaxResult.success(stu);
    }



    /**
     * 一个人的跟进列表 有stuentId      /student/followListById
     *
     * @param studentContactRecord
     * @return
     */
    @PostMapping("/followListById")
    public AjaxResult followListById(@RequestBody StudentContactRecord studentContactRecord) {
        WxUserDto wxUser = getWxUser();
        studentContactRecord.setOrgId(wxUser.getOrgIdLong());
        List<StudentContactRecord> list = studentContactRecordService.followListById(studentContactRecord);
        return AjaxResult.success(list);
    }

    //---------------------开班试听---------------------------------

    /**
     * 班级课程关联列表   /student/classCourseList
     */
    @PostMapping("/classCourseList")
    public AjaxResult classCourseList(@RequestBody StudentClass tClass) {
        WxUserDto wxUser = getWxUser();
        tClass.setOrgId(wxUser.getOrgIdLong());
        StudentClass list = studentClassService.classCourseList(tClass);
        return AjaxResult.success(list);
    }


    //--------------财务转课退课------------------------------------------
    /**
     * 模糊查询报名上课学员（加分页）  /student/allStudent
     *
     * @param student
     * @return
     */
    @GetMapping("/allStudent")
    public WxTableDataInfo allStudent(Student student) {
        WxUserDto wxUser = getWxUser();
        student.setOrgId(wxUser.getOrgIdLong());
        startPage();
        List<Student> stu = studentService.allStudent(student);
        return getWxDataTable(stu);
    }

    /**
     * 学生报读过得课程    /tStudentCourse/courseList
     */
    @PostMapping("/studentCourseList")
    public AjaxResult courseList(@RequestBody TStudentCourseVo tStudentCourseVo) {
        WxUserDto wxUser = getWxUser();
        //机构id
        tStudentCourseVo.setOrgId(wxUser.getOrgIdLong());
        //当前登录人id
        tStudentCourseVo.setCreator(wxUser.getUserId());
        List<TStudentCourseDto>  tStudentCourseDtos = studentCourseService.courseList(tStudentCourseVo);
        return AjaxResult.success(tStudentCourseDtos);
    }


    /**
     * 学生报读过得课程的订单列表  /tStudentCourse/courseOrderList
     */
    @PostMapping("/studentCourseOrderList")
    public AjaxResult courseOrderList(@RequestBody TStudentCourseVo tStudentCourseVo) {
        WxUserDto wxUser = getWxUser();
        //机构id
        tStudentCourseVo.setOrgId(wxUser.getOrgIdLong());
        //当前登录人id
        tStudentCourseVo.setCreator(wxUser.getUserId());
        List<TStudentCourseDto>  tStudentCourseDtos = studentCourseService.courseOrderList(tStudentCourseVo);
        return AjaxResult.success(tStudentCourseDtos);
    }





    /**
     * 转课   /tStudentCourse/transferOrder
     */
    @PostMapping("/studentCourseTransferOrder")
    public AjaxResult transferOrder(@RequestBody TransferOrderVo transferOrderVo) {
        WxUserDto wxUser = getWxUser();
        List<TStudentCourseVo> tStudentCourseVos = transferOrderVo.gettStudentCourseVos();
        for (TStudentCourseVo u : tStudentCourseVos) {
            //机构id
            u.setOrgId(wxUser.getOrgIdLong());
            //当前登录人id
            u.setEditor(wxUser.getUserId());
        }

        StudentCourseVo studentCourseVo = transferOrderVo.getStudentCourseVo();
        //机构id
        studentCourseVo.setOrgId(wxUser.getOrgIdLong());
        //当前登录人id
        studentCourseVo.setCreator(wxUser.getUserId());
        String  code = studentCourseService.transferOrder(transferOrderVo);
        return AjaxResult.success(code);
    }

    /**
     * 退课  /tStudentCourse/refundOrder
     */
    @PostMapping("/studentCourseRefundOrder")
    public AjaxResult refundOrder(@RequestBody List<TStudentCourseVo> tStudentCourseVos) {
        WxUserDto wxUser = getWxUser();
        tStudentCourseVos.stream().forEach(u->{
            //机构id
            u.setOrgId(wxUser.getOrgIdLong() );
            //当前登录人id
            u.setEditor(wxUser.getUserId());
        });

        String  code = studentCourseService.refundOrder(tStudentCourseVos,"订单处理-退课");
        return AjaxResult.success(code);
    }


}
